package arehart.tyler;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.View;
import android.widget.Chronometer;
import android.widget.TextView;
import arehart.tyler.BeepService.LocalBinder;

public class SonarGPSActivity extends Activity {

	private Chronometer mChronometer;
	private TextView distancetext;
	private BeepService mService;
	boolean mBound = false;
	boolean running;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mChronometer = (Chronometer) findViewById(R.id.chronometer1);
		distancetext = (TextView) findViewById(R.id.textView1);
		running = true;
		checkStatus();

	}
	
	private void checkStatus() {

		Timer t = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				if (mBound)
					distancetext.setText(mService.distancetext);
				if (running) {
					checkStatus();
				}
			}
		};
		t.schedule(task, 500);
	}

	@Override
	protected void onStart() {
		super.onStart();
		// Bind to LocalService
		Intent intent = new Intent(this, BeepService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocalBinder binder = (LocalBinder) arg1;
			mService = binder.getService();
			mBound = true;
			checkStatus();
		}

		public void onServiceDisconnected(ComponentName arg0) {
			mBound = false;
		}

	};

	public void start(View view) {
		mService.start(view);
		mChronometer.setBase(SystemClock.elapsedRealtime());
		mChronometer.start();
	}

	public void stop(View view) {
		mService.stop(view);
		mChronometer.stop();

	}
	
	public void setTarget(View view) {
		mService.setTarget(view);
	}

	@Override
	protected void onResume() {
		super.onResume();
		running = true;
		checkStatus();
		if (mBound)
			mService.goLoud();
		
		// requestUpdates();
		//
		// if (running) {
		// beepSoon();
		//
		// }

	}

	@Override
	protected void onPause() {
		super.onPause();
		running = false;
		if (mBound)
			mService.goQuiet();

		// running = false;
		// locationManager.removeUpdates(locationListener);

	}
}